package cn.manyufun.myf.ui.common;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import java.text.SimpleDateFormat;
import java.util.List;

import butterknife.BindView;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.ArticleListBean;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.bean.ComicsSummary;
import cn.manyufun.myf.bean.FollowListBean;
import cn.manyufun.myf.bean.NewsSummary;
import cn.manyufun.myf.bean.ReplyBean;
import cn.manyufun.myf.bean.ReplyListBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonwidget.LoadingTip;
import cn.manyufun.myf.common.commonwidget.NormalTitleBar;
import cn.manyufun.myf.common.irecyclerview.IRecyclerView;
import cn.manyufun.myf.common.irecyclerview.OnLoadMoreListener;
import cn.manyufun.myf.common.irecyclerview.OnRefreshListener;
import cn.manyufun.myf.common.irecyclerview.universaladapter.ViewHolderHelper;
import cn.manyufun.myf.common.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import cn.manyufun.myf.common.irecyclerview.widget.LoadMoreFooterView;
import cn.manyufun.myf.ui.common.Presenter.CommonListPresenter;
import cn.manyufun.myf.ui.common.contact.CommonListContract;
import cn.manyufun.myf.ui.common.model.CommonListModel;
import cn.manyufun.myf.ui.main.adapter.FollowListAdapter;
import cn.manyufun.myf.ui.news.activity.NewsDetailActivity;

import static cn.manyufun.myf.app.AppConstant.TYPE_ARTICLE;
import static cn.manyufun.myf.app.AppConstant.TYPE_ARTICLE_COMMENT;
import static cn.manyufun.myf.app.AppConstant.TYPE_COMMENT;
import static cn.manyufun.myf.common.commonutils.RequestBodyUtils.getLikeRequestBody;
import static cn.manyufun.myf.common.commonutils.TimeUtil.getfriendlyTime;

public class CommonListActivity extends BaseActivity<CommonListPresenter, CommonListModel> implements CommonListContract.View, OnRefreshListener, OnLoadMoreListener {
    public final static String EXTRA_DATA_OTHER = "data_other";
    public final static String EXTRA_DATA_TYPE = "data_type";
    private static final int PAGE_SIZE = 20;

    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.irc)
    IRecyclerView irc;
    @BindView(R.id.loadedTip)
    LoadingTip loadedTip;
    private int mType;
    private Object mOther;
    private int mStartPage = 1;

    private FollowListAdapter followListAdapter;
    CommonRecycleViewAdapter<ReplyBean> commentAdapter;
    CommonRecycleViewAdapter<NewsSummary> articleAdapter;


    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, CommonListActivity.class);
        if (bundle != null)
            intent.putExtras(bundle);
        context.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_common_list;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        mType = intent.getIntExtra(EXTRA_DATA_TYPE, 0);
        if (mType == TYPE_COMMENT || mType == TYPE_ARTICLE || mType == TYPE_ARTICLE_COMMENT) {
            mOther = intent.getLongExtra(EXTRA_DATA_OTHER, 0);
        }
        ntb.setOnBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        irc.setLayoutManager(new LinearLayoutManager(this));

        irc.setOnRefreshListener(this);
        irc.setOnLoadMoreListener(this);
        initByType(mType);
//        mPresenter.getCommonListDataRequest(mStartPage, PAGE_SIZE, mType);
    }

    private void initComicsAdapter() {
        followListAdapter = new FollowListAdapter(this, R.layout.common_comics_item, mType);
        irc.setAdapter(followListAdapter);
        mPresenter.getCommonListDataRequest(mStartPage, PAGE_SIZE, mType);
    }

    private void initByType(int type) {
        switch (type) {
            case AppConstant.TYPE_RECOMMEND:
                ntb.setTitleText("为你推荐");
                initComicsAdapter();
                break;
            case AppConstant.TYPE_HOT:
                ntb.setTitleText("今日热门");
                initComicsAdapter();
                break;
            case AppConstant.TYPE_RANK:
                ntb.setTitleText("排行榜");
                initComicsAdapter();
                break;
            case TYPE_COMMENT:
            case TYPE_ARTICLE_COMMENT:
                ntb.setTitleText("全部短评");
                initCommentAdapter();
                break;
            case TYPE_ARTICLE:
                ntb.setTitleText("全部漫评");
                initArticleAdapter();
                break;
        }
    }

    private void initArticleAdapter() {
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        articleAdapter = new CommonRecycleViewAdapter<NewsSummary>(this, R.layout.layout_item_article) {
            @Override
            public void convert(ViewHolderHelper holder, final NewsSummary newsSummary) {
                holder.setText(R.id.tv_author_name, newsSummary.getAuthorName());
                holder.setImageRoundUrl(R.id.iv_head, newsSummary.getAuthorImageUrl());
                holder.setRating(R.id.rb_score, newsSummary.getScore());
                holder.setText(R.id.tv_title, newsSummary.getTitle());
                holder.setText(R.id.tv_content, newsSummary.getBriefInfo());
                holder.setText(R.id.tv_like, newsSummary.getLikeNum() + "");
                holder.setText(R.id.tv_comment, newsSummary.getCommentNum() + "");
                holder.setText(R.id.tv_view, newsSummary.getViewNum() + "");
                holder.setText(R.id.tv_publish_time, dateFormat.format(newsSummary.getPublishTime()));

                holder.setOnClickListener(R.id.ll_root, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundle = new Bundle();
                        bundle.putLong(NewsDetailActivity.EXTRA_DATA_ARTICLE_ID, newsSummary.getReferenceId());
                        bundle.putString(NewsDetailActivity.EXTRA_DATA_ARTICLE_TITLE, newsSummary.getTitle());
                        bundle.putString(NewsDetailActivity.EXTRA_DATA_ARTICLE_IMG, newsSummary.getCoverImageUrl());
                        NewsDetailActivity.startAction(mContext, bundle);
                    }
                });
            }
        };
        irc.setAdapter(articleAdapter);
        mPresenter.getComicArticleListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
    }

    private void initCommentAdapter() {
        commentAdapter = new CommonRecycleViewAdapter<ReplyBean>(this, R.layout.layout_item_comment) {
            @Override
            public void convert(final ViewHolderHelper holder, final ReplyBean newsSummary) {
                holder.setText(R.id.tv_author_name, newsSummary.UserName);
                holder.setImageRoundUrl(R.id.iv_head, newsSummary.UserImageUrl);
                holder.setRating(R.id.rb_score, newsSummary.Score);
                holder.setText(R.id.tv_content, newsSummary.Content);
                holder.setText(R.id.tv_like, newsSummary.LikeNum + "");
                holder.setText(R.id.tv_publish_time, getfriendlyTime(newsSummary.ReplyTime.getTime()));
                holder.setOnClickListener(R.id.iv_like, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Api.getDefault(HostType.manyufun).like(getLikeRequestBody(1, newsSummary.ReplyId))
                                .compose(RxSchedulers.<BaseBean>io_main())
                                .subscribe(new RxSubscriber<BaseBean>(CommonListActivity.this, false) {
                                    @Override
                                    public void onStart() {
                                        super.onStart();
                                    }

                                    @Override
                                    protected void _onNext(BaseBean posterBean) {
                                        if (posterBean.getSuccess().equals("1")) {
                                            showShortToast("点赞 + 1");
                                            holder.setText(R.id.tv_like, ++newsSummary.LikeNum + "");
                                        } else {

//                                            showShortToast(posterBean.getErrorMsg());
                                            showShortToast("已点赞");
                                        }

                                    }

                                    @Override
                                    protected void _onError(String message) {
                                        showShortToast(message);
                                    }
                                });
                    }
                });

            }
        };
        irc.setAdapter(commentAdapter);
        if (mType == TYPE_COMMENT)
            mPresenter.getComicsCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        else if (mType == TYPE_ARTICLE_COMMENT)
            mPresenter.getArticleCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
    }

    @Override
    public void onRefresh() {
        mStartPage = 1;
        //发起请求
        irc.setRefreshing(true);
        refreshByType();
    }

    private void refreshByType() {
        if (mType == AppConstant.TYPE_RECOMMEND || mType == AppConstant.TYPE_HOT || mType == AppConstant.TYPE_RANK) {
            followListAdapter.getPageBean().setRefresh(true);
            followListAdapter.clear();
            mPresenter.getCommonListDataRequest(mStartPage, PAGE_SIZE, mType);
        } else if (mType == TYPE_COMMENT) {
            commentAdapter.getPageBean().setRefresh(true);
            commentAdapter.clear();
            mPresenter.getComicsCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        } else if (mType == TYPE_ARTICLE) {
            articleAdapter.getPageBean().setRefresh(true);
            articleAdapter.clear();
            mPresenter.getComicArticleListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        } else if (mType == TYPE_ARTICLE_COMMENT) {
            commentAdapter.getPageBean().setRefresh(true);
            commentAdapter.clear();
            mPresenter.getArticleCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        }
    }

    @Override
    public void onLoadMore(View loadMoreView) {
        //发起请求
        irc.setLoadMoreStatus(LoadMoreFooterView.Status.LOADING);
        loadMoreByType();
    }

    private void loadMoreByType() {
        if (mType == AppConstant.TYPE_RECOMMEND || mType == AppConstant.TYPE_HOT || mType == AppConstant.TYPE_RANK) {
            followListAdapter.getPageBean().setRefresh(false);
            mPresenter.getCommonListDataRequest(mStartPage, PAGE_SIZE, mType);
        } else if (mType == AppConstant.TYPE_COMMENT) {
            commentAdapter.getPageBean().setRefresh(false);
            mPresenter.getComicsCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        } else if (mType == AppConstant.TYPE_ARTICLE_COMMENT) {
            commentAdapter.getPageBean().setRefresh(false);
            mPresenter.getArticleCommentListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        } else if (mType == TYPE_ARTICLE) {
            articleAdapter.getPageBean().setRefresh(false);
            mPresenter.getComicArticleListDataRequest(mStartPage, PAGE_SIZE, (long) mOther);
        }
    }

    @Override
    public void showLoading(String title) {
//        if (followListAdapter.getPageBean().isRefresh()) {
//            if (followListAdapter.getSize() <= 0) {
//                loadedTip.setLoadingTip(LoadingTip.LoadStatus.loading);
//            }
//        }
    }

    @Override
    public void stopLoading() {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.finish);
    }

    @Override
    public void showErrorTip(String msg) {
//        if (followListAdapter.getPageBean().isRefresh()) {
//            if (followListAdapter.getSize() <= 0) {
//                loadedTip.setLoadingTip(LoadingTip.LoadStatus.error);
        loadedTip.setTips(msg);
//            }
//            irc.setRefreshing(false);
//        } else {
//            irc.setLoadMoreStatus(LoadMoreFooterView.Status.ERROR);
//        }
    }

    @Override
    public void returnCommonListData(FollowListBean followListBean, int type) {
        List<ComicsSummary> newsSummaries = followListBean.getFollowList();
        if (newsSummaries != null && newsSummaries.size() > 0) {
            mStartPage += 20;
            if (followListAdapter.getPageBean().isRefresh()) {
                irc.setRefreshing(false);
                followListAdapter.replaceAll(newsSummaries);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                if (newsSummaries.size() > 0) {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
                    followListAdapter.addAll(newsSummaries);
                } else {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
                }
            }
        } else {
//            followListAdapter.clear();
            irc.setRefreshing(false);
            if (mStartPage == 1) {
                loadedTip.setLoadingTip(LoadingTip.LoadStatus.empty);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
            }
        }
    }

    @Override
    public void returnComicsCommentListData(ReplyListBean replyListBean) {
        List<ReplyBean> newsSummaries = replyListBean.getReplyList();
        if (newsSummaries != null && newsSummaries.size() > 0) {
            mStartPage += 20;
            if (commentAdapter.getPageBean().isRefresh()) {
                irc.setRefreshing(false);
                commentAdapter.replaceAll(newsSummaries);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                if (newsSummaries.size() > 0) {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
                    commentAdapter.addAll(newsSummaries);
                } else {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
                }
            }
        } else {
            irc.setRefreshing(false);
            if (mStartPage == 1) {
                loadedTip.setLoadingTip(LoadingTip.LoadStatus.empty);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
            }
        }
    }

    @Override
    public void returnComicArticleListData(ArticleListBean articleListBean) {
        List<NewsSummary> newsSummaries = articleListBean.getArticleList();
        if (newsSummaries != null && newsSummaries.size() > 0) {
            mStartPage += 20;
            if (articleAdapter.getPageBean().isRefresh()) {
                irc.setRefreshing(false);
                articleAdapter.replaceAll(newsSummaries);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                if (newsSummaries.size() > 0) {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
                    articleAdapter.addAll(newsSummaries);
                } else {
                    irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
                }
            }
        } else {
            irc.setRefreshing(false);
            if (mStartPage == 1) {
                loadedTip.setLoadingTip(LoadingTip.LoadStatus.empty);
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.GONE);
            } else {
                irc.setLoadMoreStatus(LoadMoreFooterView.Status.THE_END);
            }
        }
    }
}
